<template>
  <div id="studentAllocation">
    <h1>学员分配教练</h1>
    <table>
      <thead>
      <tr>
        <th>学员 ID</th>
        <th>学员名字</th>
        <th>学员意愿教练 ID</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="student in students" :key="student.id">
        <td>{{ student.id }}</td>
        <td>{{ student.name }}</td>
        <td>{{ student.coachWishId }}</td>
        <!-- 省略 template 中的其他部分 -->

        <td>
          <button class='refuse-button' @click="refuseCoach(student.id)">拒绝分配</button>
        </td>

        <!-- 省略 template 中的其他部分 -->
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "StudentAllocation",
  data() {
    return {
      students: [],
    };
  },
  created() {
    this.fetchStudents();
  },
  methods: {
    async fetchStudents() {
      try {
        const url = "http://localhost:8081/student/list";
        const response = await axios.get(url);

        this.students = response.data.data.map(student => {
          return {
            id: student.id, // 根据api返回的字段修改
            name: student.username,
            coachWishId: student.coach_id, // 根据api返回的字段修改
          };
        });
      } catch (error) {
        console.error("Fetching students error:", error);
      }
    },
    async refuseCoach(studentId) {
      try {
        const url = `http://localhost:8081/student/refuse/${studentId}`;
        const response = await axios.post(url);

        if (response.data.code === 20000) {

          this.fetchStudents(); // 刷新学员数据，以便显示最新状态
          this.$message.success("拒绝成功！");
        } else {
          this.$message.error("拒绝失败！");
        }
      } catch (error) {
        console.error("分配拒绝错误:", error);
      }
    },
  },
};
</script>

<style>
h1 {
  text-align: center;
  margin-bottom: 40px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ccc;
  padding: 8px 0;
  text-align: center;
}

thead tr {
  background-color: #f2f2f2;
}

tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.refuse-button{
  background-color: #f44336;
  color: white;
  border: none;
  cursor: pointer;
  padding: 8px 16px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin: 2px 2px;
  transition-duration: 0.4s;
}

button:hover {
  background-color: #c0392b;
}
</style>